<template>
  <a-table
    ref="table"
    :rowKey="record => record.ID"
    :columns="columns"
    :dataSource="fileList"
    :scroll="{x: true}"
    :pagination="{ showTotal: total => `共 ${total} 条` }"
  >
    <span slot="serial" slot-scope="text, record, index">
      {{ index + 1 }}
    </span>
    <span slot="description" slot-scope="text">
      <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
    </span>
    <span slot="time" slot-scope="text">{{ text | moment('YYYY-MM-DD') }}</span>
    <span slot="action" slot-scope="text, record">
      <template>
        <template v-if="record.isPreview">
          <a class="m-r-10" href="#" @click="handlePreview(record)">预览</a>
        </template>
        <template v-else>
          <a :href="baseUrl + record.WJLJ" target="_self">下载</a>
        </template>
      </template>
    </span>
  </a-table>
</template>

<script>
import { Ellipsis } from '@/components'
const columns = [
{
    title: '序号',
    width: '80px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '文件名称',
    key: 'name',
    dataIndex: 'WJMC',
    scopedSlots: { customRender: 'description' }
  },
  {
    title: '文件类型',
    key: 'type',
    dataIndex: 'WJLX'
  },
  {
    title: '文件分类',
    key: 'category',
    dataIndex: 'CS_WJMC'
  },
  {
    title: '上传时间',
    key: 'time',
    dataIndex: 'SCSJ',
    scopedSlots: { customRender: 'time' }
  },
  {
    title: '文件描述',
    key: 'description',
    dataIndex: 'WJSM',
    scopedSlots: { customRender: 'description' }
  },
  {
    title: '操作',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'FilePreview',
  props: {
    category: {
      type: String,
      default: ''
    },
    fileData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  components: {
    Ellipsis
  },
  watch: {
    fileData: {
      handler: function (newVal, oldVal) {
        if (newVal) {
          this.fileList = newVal.map(item => {
            item.isPreview = ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp', 'svg'].includes(item.WJLX)
            return item
          })
        }
      },
      immediate: true
    }
  },
  data () {
    this.columns = columns
    return {
      baseUrl: process.env.VUE_APP_API_BASE_URL,
      fileList: []
    }
  },
  methods: {
    handlePreview (record) {
      const imgList = []
      this.fileData.forEach(item => {
        if (item.isPreview) {
          imgList.push(this.baseUrl + item.WJLJ)
        }
      })
      const imageIndex = imgList.findIndex(e => e.indexOf(record.WJLJ) !== -1)
      this.$viewerApi({
        images: imgList,
        options: {
          initialViewIndex: imageIndex
        }
      })
    }
  }
}
</script>
